/**
 * 收藏页面脚本
 */


const API = {
  getFavorites: () => {
    // 模拟数据
    const favorites = [
      { id: 1, title: "Item 1", type: "Movie", year: "2020", timestamp: Date.now(), poster: "images/placeholder.jpg" },
      {
        id: 2,
        title: "Item 2",
        type: "TV Show",
        year: "2021",
        timestamp: Date.now() - 10000,
        poster: "images/placeholder.jpg",
      },
      {
        id: 3,
        title: "Item 3",
        type: "Movie",
        year: "2022",
        timestamp: Date.now() - 20000,
        poster: "images/placeholder.jpg",
      },
    ]
    return favorites
  },
  removeFavorite: (id) => {
    console.log(`Removing favorite with id: ${id}`)
    return true // 模拟删除成功
  },
}

const UI = {
  showToast: (message) => {
    alert(message) // 简单地使用 alert 模拟 toast
  },
}

document.addEventListener("DOMContentLoaded", () => {
  // 加载收藏列表
  loadFavorites()

  // 初始化排序
  initSorting()

  // 添加动画效果
  addAnimations()
})

/**
 * 加载收藏列表
 * @param {string} sort 排序方式
 * @param {string} order 排序顺序
 */
function loadFavorites(sort = "date", order = "desc") {
  const favoritesGrid = document.getElementById("favoritesGrid")
  const favoriteCount = document.getElementById("favoriteCount")

  if (!favoritesGrid) return

  // 获取收藏列表
  const favorites = API.getFavorites()

  // 更新收藏数量
  if (favoriteCount) {
    favoriteCount.textContent = favorites.length
  }

  // 清空加载中状态
  favoritesGrid.innerHTML = ""

  if (favorites.length === 0) {
    favoritesGrid.innerHTML = `
      <div class="empty-state">
        <i class="ri-heart-line"></i>
        <h2>暂无收藏</h2>
        <p>您还没有收藏任何内容</p>
        <a href="index.html" class="btn btn-primary">
          <i class="ri-home-line"></i>
          返回首页
        </a>
      </div>
    `
    return
  }

  // 排序收藏列表
  const sortedFavorites = sortFavorites(favorites, sort, order)

  // 渲染收藏列表
  sortedFavorites.forEach((item) => {
    const card = createFavoriteCard(item)
    favoritesGrid.appendChild(card)
  })
}

/**
 * 排序收藏列表
 * @param {Array} favorites 收藏列表
 * @param {string} sort 排序方式
 * @param {string} order 排序顺序
 * @returns {Array} 排序后的收藏列表
 */
function sortFavorites(favorites, sort, order) {
  const sortedFavorites = [...favorites]

  // 根据排序方式排序
  switch (sort) {
    case "date":
      sortedFavorites.sort((a, b) => a.timestamp - b.timestamp)
      break
    case "title":
      sortedFavorites.sort((a, b) => a.title.localeCompare(b.title))
      break
    case "year":
      sortedFavorites.sort((a, b) => {
        const yearA = a.year ? Number.parseInt(a.year) : 0
        const yearB = b.year ? Number.parseInt(b.year) : 0
        return yearA - yearB
      })
      break
    default:
      sortedFavorites.sort((a, b) => a.timestamp - b.timestamp)
  }

  // 根据排序顺序反转
  if (order === "desc") {
    sortedFavorites.reverse()
  }

  return sortedFavorites
}

/**
 * 创建收藏卡片
 * @param {Object} item 收藏项
 * @returns {HTMLElement} 收藏卡片元素
 */
function createFavoriteCard(item) {
  const card = document.createElement("div")
  card.className = "favorite-card"

  const posterUrl = item.poster || "images/placeholder.jpg"

  card.innerHTML = `
    <div class="favorite-poster">
      <img src="${posterUrl}" alt="${item.title}" loading="lazy">
      <button class="favorite-remove" data-id="${item.id}" title="移除收藏">
        <i class="ri-delete-bin-line"></i>
      </button>
    </div>
    <div class="favorite-info">
      <h3 class="favorite-title">${item.title}</h3>
      <div class="favorite-meta">
        <span>${item.type || "未知类型"}</span>
        <span>${item.year || "未知年份"}</span>
      </div>
    </div>
  `

  // 添加点击事件
  card.addEventListener("click", (e) => {
    // 如果点击的是移除按钮，则不跳转
    if (e.target.closest(".favorite-remove")) {
      e.preventDefault()
      return
    }

    // 跳转到详情页
    window.location.href = `detail.html?id=${item.id}`
  })

  // 添加移除收藏事件
  const removeBtn = card.querySelector(".favorite-remove")
  if (removeBtn) {
    removeBtn.addEventListener("click", (e) => {
      e.stopPropagation()
      const id = Number.parseInt(removeBtn.dataset.id)

      // 确认是否移除
      if (confirm("确定要移除这个收藏吗？")) {
        // 移除收藏
        const success = API.removeFavorite(id)

        if (success) {
          // 显示成功提示
          UI.showToast("已移除收藏")

          // 移除卡片元素
          card.classList.add("fade-out")
          setTimeout(() => {
            card.remove()

            // 更新收藏数量
            const favoriteCount = document.getElementById("favoriteCount")
            if (favoriteCount) {
              const count = Number.parseInt(favoriteCount.textContent) - 1
              favoriteCount.textContent = count
            }

            // 如果没有收藏了，显示空状态
            const favoritesGrid = document.getElementById("favoritesGrid")
            if (favoritesGrid && favoritesGrid.children.length === 0) {
              loadFavorites()
            }
          }, 300)
        }
      }
    })
  }

  return card
}

/**
 * 初始化排序
 */
function initSorting() {
  const sortItems = document.querySelectorAll("[data-sort]")
  const orderItems = document.querySelectorAll("[data-order]")
  const sortLabel = document.getElementById("sortLabel")
  const orderLabel = document.getElementById("orderLabel")

  // 当前排序方式和顺序
  let currentSort = "date"
  let currentOrder = "desc"

  // 监听排序选项点击
  sortItems.forEach((item) => {
    item.addEventListener("click", () => {
      // 移除所有选项的活跃状态
      sortItems.forEach((i) => i.classList.remove("active"))

      // 添加当前选项的活跃状态
      item.classList.add("active")

      // 获取排序方式
      const sort = item.dataset.sort
      currentSort = sort

      // 更新排序标签
      if (sortLabel) {
        sortLabel.textContent = getSortLabel(sort)
      }

      // 重新加载收藏列表
      loadFavorites(currentSort, currentOrder)
    })
  })

  // 监听排序顺序点击
  orderItems.forEach((item) => {
    item.addEventListener("click", () => {
      // 移除所有选项的活跃状态
      orderItems.forEach((i) => i.classList.remove("active"))

      // 添加当前选项的活跃状态
      item.classList.add("active")

      // 获取排序顺序
      const order = item.dataset.order
      currentOrder = order

      // 更新排序顺序标签
      if (orderLabel) {
        orderLabel.textContent = order === "asc" ? "升序" : "降序"
      }

      // 更新排序顺序图标
      const orderIcon = document.querySelector("#orderDropdown .dropdown-toggle i:first-child")
      if (orderIcon) {
        orderIcon.className = order === "asc" ? "ri-sort-asc" : "ri-sort-desc"
      }

      // 重新加载收藏列表
      loadFavorites(currentSort, currentOrder)
    })
  })
}

/**
 * 获取排序标签
 * @param {string} sort 排序方式
 * @returns {string} 排序标签
 */
function getSortLabel(sort) {
  switch (sort) {
    case "date":
      return "添加日期"
    case "title":
      return "标题"
    case "year":
      return "发行年份"
    default:
      return "添加日期"
  }
}

/**
 * 添加动画效果
 */
function addAnimations() {
  // 为页面标题添加动画
  const pageTitle = document.querySelector(".page-title")
  if (pageTitle) {
    pageTitle.classList.add("fade-in")
  }

  // 为筛选栏添加动画
  const filterSortBar = document.querySelector(".filter-sort-bar")
  if (filterSortBar) {
    filterSortBar.style.animationDelay = "0.2s"
    filterSortBar.classList.add("fade-in")
  }
}

// 添加淡出动画类
document.head.insertAdjacentHTML(
  "beforeend",
  `
  <style>
    .fade-out {
      animation: fade-out 0.3s ease forwards;
    }
    
    @keyframes fade-out {
      from {
        opacity: 1;
        transform: scale(1);
      }
      to {
        opacity: 0;
        transform: scale(0.8);
      }
    }
  </style>
`,
)
